#!/usr/bin/env python3
# filename: extensions.py

import os

from flask_bcrypt import Bcrypt
from flask_oauthlib.client import OAuth
from flask import session
from flask_login import LoginManager
from flask_principal import Principal, Permission, RoleNeed
from flask_admin import Admin

# new Bcrypy instance
bcrypt = Bcrypt()
oauth = OAuth()
login_manager = LoginManager()
principals = Principal()
flask_admin = Admin()

# Init the role permission via RoleNeed(Need).
admin_permission = Permission(RoleNeed('admin'))
poster_permission = Permission(RoleNeed('poster'))
default_permission = Permission(RoleNeed('default'))

login_manager.login_view = "main.login"
login_manager.session_protection = "strong"
login_manager.login_message = "Please login to access this page."
login_manager.login_message_category = "info"

client_id = os.environ.get("GITHUB_CLIENT_ID")
client_secret = os.environ.get("GITHUB_CLIENT_SECRET")

# github login api
# create the oauth object for github.
github = oauth.remote_app(
    'github',
    consumer_key=client_id,
    consumer_secret=client_secret,
    request_token_params={'scope': 'user:email'},
    base_url='https://api.github.com/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize'
)


@github.tokengetter
def get_github_oauth_token():
    return session.get('github_token')


@login_manager.user_loader
def load_user(user_id):
    """Load the user's info"""

    from hzsaiblog.models import User
    return User.query.filter_by(id=user_id).first()
